import type { Router, RouteRecordRaw } from "vue-router";
import { snakeCaseStyle } from "ph-utils";

type DynamicRouteRaw = RouteRecordRaw & {
  /**
   * 路由参数, 将会自动拼接到路由地址上, 比如: ['id'] -> /:id
   */
  params?: string[];
};

interface DynamicRouteConfig {
  [index: string]: DynamicRouteRaw;
}

const ROUTE_NAME_REG = /\/src\/views\/(.*?)\.vue/;

function addParamsToPath(path: string, params: string[]) {
  return path + params.map((p) => `/:${p}`).join("");
}

export const routes = [];
export function addDynamicRoutes(
  router: Router,
  config?: DynamicRouteConfig | ((name: string) => DynamicRouteRaw)
) {
  const modules = import.meta.glob("/src/views/**/*.vue");

  for (const modulePath in modules) {
    const moduleNameMatch = modulePath.match(ROUTE_NAME_REG);
    if (moduleNameMatch != null) {
      const name = moduleNameMatch[1];
      let routePath = snakeCaseStyle(name, "_");
      if (name === "Home") {
        routePath = "";
      }
      let routeRecord: DynamicRouteRaw = {
        name,
        component: modules[modulePath],
        path: `/${routePath}`,
      };
      if (config != null) {
        if (typeof config === "function") {
          routeRecord = { ...(routeRecord as any), ...config(name) };
        } else {
          routeRecord = { ...routeRecord, ...config };
        }
      }
      if (routeRecord.params != null && routeRecord.params.length > 0) {
        routeRecord.path = addParamsToPath(
          routeRecord.path,
          routeRecord.params
        );
        routeRecord.props = true;
        delete routeRecord.params;
      }
      router.addRoute(routeRecord);
    }
  }
}
